package org.lc.eic.messagingsystem.activemq;

import javax.jms.Connection;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.lc.eic.messageendpoint.InboundEndpoint;
import org.lc.eic.messageendpoint.OutboundEndpoint;
import org.lc.eic.messagingsystem.MessagingSystemReference;
import org.lc.eic.messagingsystem.exception.RegistrationException;
import org.lc.eic.messagingsystem.exception.StartMessagingException;
import org.lc.eic.messagingsystem.exception.StopMessagingException;

public class ActiveMQMessagingSystem implements MessagingSystemReference {

	
	private Connection connection;
	

	public ActiveMQMessagingSystem(String brokerUrl) throws JMSException{
		ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(brokerUrl);
		this.connection = activeMQConnectionFactory.createConnection();
		
	}

	public void registerInboundEndpoint(InboundEndpoint inboundEndpoint,
			String queueIdentifier) throws RegistrationException {

		try {
			
			Session session = connection.createSession(false,
					Session.AUTO_ACKNOWLEDGE);
			// create our request and response queues
			Queue queue = session.createQueue(queueIdentifier);

			// and attach a consumer and producer to them
			MessageConsumer consumer = session.createConsumer(queue);
			consumer.setMessageListener(new MessageListener(inboundEndpoint));

			
		} catch (JMSException e) {
			throw new RegistrationException(
					"Failed create connection to activemq-queue: "
							+ queueIdentifier);
		}

	}

	

	public void registerOutboundEndpoint(OutboundEndpoint messageEndpoint,
			String queueIdentifier) throws RegistrationException {
		try {
			
			Session session = connection.createSession(false,
					Session.AUTO_ACKNOWLEDGE);
			// create our request and response queues
			Queue queue = session.createQueue(queueIdentifier);

			// and attach a consumer and producer to them
			MessageProducer producer = session.createProducer(queue);

			MessagingReference messagingReference = new MessagingReference(
					session, producer);

			messageEndpoint.setMessagingRef(messagingReference);

		} catch (JMSException e) {
			throw new RegistrationException(
					"Failed create connection to activemq-queue: "
							+ queueIdentifier);
		}

	}

	public void startMessaging() throws StartMessagingException {
				
		try {
			connection.start();
		} catch (JMSException e) {
			throw new StartMessagingException("Failed start messaging. ", e);
		}
		
	}

	public void stopMessaging() throws StopMessagingException {
		try {
			connection.stop();
		} catch (JMSException e) {
			throw new StopMessagingException("Exception occurred when stopping connection. ", e);
		}

	}

}
